package cn.ug.product.service.impl;

import cn.ug.core.ensure.Ensure;
import cn.ug.pay.bean.status.CommonConstants;
import cn.ug.product.bean.request.CreateTradeTimeParamBean;
import cn.ug.product.bean.request.TradeTemplateParam;
import cn.ug.product.bean.response.ProductFindBean;
import cn.ug.product.bean.response.ProductTradeTimeBean;
import cn.ug.product.bean.response.TradeTemplateBean;
import cn.ug.product.mapper.ProductMapper;
import cn.ug.product.mapper.ProductTradeTimeMapper;
import cn.ug.product.mapper.TradeTemplateMapper;
import cn.ug.product.mapper.entity.Product;
import cn.ug.product.mapper.entity.TradeTemplate;
import cn.ug.product.service.ProductTradeTimeService;
import cn.ug.util.UF;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品交易时间段
 * @author  ywl
 * @date 2018-05-01
 */
@Service
public class ProductTradeTimeServiceImpl implements ProductTradeTimeService {

    @Resource
    private ProductTradeTimeMapper productTradeTimeMapper;

    @Resource
    private TradeTemplateMapper tradeTemplateMapper;

    @Resource
    private ProductMapper productMapper;

    @Override
    public List<ProductTradeTimeBean> findList(String productId) {
        List<ProductTradeTimeBean> list = productTradeTimeMapper.findList(productId);
        return list;
    }

    @Override
    public int update(String id, String templateId) {
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", id);
        map.put("templateId", templateId);
        int num = productTradeTimeMapper.updateByPrimaryKeySelective(map);
        return num;
    }

    @Override
    public List<ProductTradeTimeBean> createTradeTimeList(CreateTradeTimeParamBean entity) {
        //验证参数合法
        Ensure.that(entity.getType()).isNull("15000003");
        Ensure.that(entity.getDay()).isNull("15000005");
        Ensure.that(entity.getUpTime()).isNull("15000004");

        //设置募集天数 原来基础+1
        Integer effectiveDay = entity.getDay() + 1;
        //返回结果
        List<ProductTradeTimeBean> resultList = new ArrayList<ProductTradeTimeBean>();
        //上线日期
        LocalDate localDate = LocalDate.parse(entity.getUpTime(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));;
        //募集天数
        int day = getMaxDay(effectiveDay, localDate);
        for(int i = 0;i< day;i++){
            List<TradeTemplate> list = tradeTemplateMapper.findDefaultTemplate(CommonConstants.Template.getName(localDate.getDayOfWeek().getValue()));
            Ensure.that(list == null || list.isEmpty() || list.size() == 1).isTrue("15000107");
            for(TradeTemplate tradeTemplate: list){
                if(entity.getType() == 2 && tradeTemplate.getType() == 2){

                }else{
                    ProductTradeTimeBean entityBean = getEntity(tradeTemplate, localDate);
                    resultList.add(entityBean);
                }
            }
            localDate = localDate.plusDays(1);
        }
        return resultList;
    }



    @Override
    public int save(String productId, List<ProductTradeTimeBean> list) {
        for(ProductTradeTimeBean entity:list){
            entity.setId(UF.getRandomUUID());
            entity.setProductId(productId);
        }
        int num = productTradeTimeMapper.insert(list);
        return num;
    }

    /**
     * 根据条件生成下个月数据
     * @param productId
     * @return
     */
    @Override
    public int createNextMonthTradeTimeList(String productId) {
        Ensure.that(productId).isNull("00000002");
        //产品
        ProductFindBean productFindBean = productMapper.queryProductById(productId);
        //查询最后一天生成时间
        String lastDay = productTradeTimeMapper.findLastDay(productFindBean.getId());
        Ensure.that(lastDay == null).isTrue("15000031");
        //最后一天时间
        LocalDate lastDate = LocalDate.parse(lastDay, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        //上线时间
        LocalDate upDate = LocalDate.parse(productFindBean.getUpTimeString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //当前时间
        LocalDate currentDate = LocalDate.now();
        //募集天数
        int  day = Integer.valueOf(productFindBean.getEffectiveDay());
        Ensure.that(currentDate.getMonth().equals(lastDate.getMonth())).isFalse("15000032");  //只有当前月份可以生成下个月数据否则
        //交易时间
        int tradeday = Integer.valueOf(ChronoUnit.DAYS.between(upDate, lastDate)+"") + 1;  //发售当日也算一天，故+1
        Ensure.that(day == tradeday).isTrue("15000033");
        //计算下个月有多少天
        int nextMonthDay = LocalDate.now().plusMonths(1).lengthOfMonth();
        //计算出下个月有效天数
        int surplusDays = day -tradeday;
        //计算出本次生成的数量
        day = surplusDays > nextMonthDay?nextMonthDay:surplusDays;

        //类型 1：活期 2:定期
        int type = productFindBean.getType() == 3?1:2;
        //返回结果
        List<ProductTradeTimeBean> resultList = new ArrayList<ProductTradeTimeBean>();
        for(int i = 0;i< day;i++){
            lastDate = lastDate.plusDays(1);
            List<TradeTemplate> list = tradeTemplateMapper.findDefaultTemplate(CommonConstants.Template.getName(lastDate.getDayOfWeek().getValue()));
            Ensure.that(list == null || list.isEmpty() || list.size() == 1).isTrue("15000107");
            for(TradeTemplate tradeTemplate: list){
                if(type == 2 && tradeTemplate.getType() == 2){

                }else{
                    ProductTradeTimeBean entityBean = getEntity(tradeTemplate, lastDate);
                    entityBean.setProductId(productId);
                    resultList.add(entityBean);
                }
            }
        }

        int num = productTradeTimeMapper.insert(resultList);
        return num;
    }

    /**
     * 组装实体
     * @param tradeTemplate
     * @param localDate
     * @return
     */
    public static ProductTradeTimeBean getEntity(TradeTemplate tradeTemplate, LocalDate localDate){
        ProductTradeTimeBean entity = new ProductTradeTimeBean();
        entity.setId(UF.getRandomUUID());
        entity.setDay(localDate.toString());
        entity.setTemplateId(tradeTemplate.getId());
        entity.setName(tradeTemplate.getName());
        entity.setType(tradeTemplate.getType());
        entity.setDetail(getDay(localDate.getDayOfWeek()+""));
        return entity;
    }

    /**
     * 初始化-目前只用到一次
     * @param name
     * @return
     */
    public static String  getDay(String name){
        Map<String,String> map = new HashMap<String,String>();
        map.put("MONDAY", "星期一");
        map.put("TUESDAY", "星期二");
        map.put("WEDNESDAY", "星期三");
        map.put("THURSDAY", "星期四");
        map.put("FRIDAY", "星期五");
        map.put("SATURDAY", "星期六");
        map.put("SUNDAY", "星期日");
        return map.get(name);
    }

    /**
     * 获取最大买金天数--不高不超过两个月
     * @param day
     * @return
     */
    public static int getMaxDay(int day,  LocalDate upTime){
        //获取当月天数
        int currentDay = LocalDate.now().lengthOfMonth();
        //获取下个月天数
        int nextDay = LocalDate.now().plusMonths(1).lengthOfMonth();
        ////当天是第几天
        int today = Integer.parseInt(upTime.format(DateTimeFormatter.ofPattern("dd")));
        //当月还剩余天数
        int currentSurplusDay = currentDay - today + 1; //要算上当天
        //两个月加起来天数
        int twoMonthAddDay = currentSurplusDay + nextDay;
        /*if(day > twoMonthAddDay){
            return twoMonthAddDay;
        }else{
            return  day;
        }*/
        return  day;
    }

    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
       /* System.out.println(date);
        date = date.plusDays(2);
        System.out.println(date);
        System.out.println(date.getDayOfWeek().getValue());*/
       /* date.plusMonths(1);
        System.out.println(date.getDayOfWeek().getValue());*/
       /* System.out.println(LocalDate.now().lengthOfMonth());
        System.out.println(LocalDate.now().plusMonths(1).lengthOfMonth());*/
       /* System.out.println(date.format(DateTimeFormatter.ofPattern("dd")));*/

        /*System.out.println(CommonConstants.Day.valueOf("MONDAY"));*/
        LocalDate localDate = LocalDate.now();
       /* int currentMonthDay = localDate.lengthOfMonth();                                     //当月有几天
        System.out.println(currentMonthDay);
        LocalDate thisMonthDate = LocalDate.now.withMonth(month.getValue());
        System.out.println(thisMonthDate);*/
        System.out.println(date.getMonth());
        LocalDate upDate = LocalDate.parse("2018-05-04 11:30:02", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        int tradeday = Integer.valueOf(ChronoUnit.DAYS.between(localDate, upDate)+"");
        System.out.println(tradeday);
    }
}
